﻿using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Microsoft.AspNetCore.Mvc;
using shenghua.Authorization;
using shenghua.Common.Dto;
using shenghua.Order.Orders.Dto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace shenghua.Order.Orders
{
    public class OrderEvaluateAppService: shenghuaAppServiceBase, IOrderEvaluateAppService
    {
        private readonly OrderEvaluateManager _orderEvaluateManager;
        private readonly IRepository<OrderEvaluate> _orderEvaluateRepository;
        private readonly IRepository<OrderDetail> _orderDetailRepository;

        public OrderEvaluateAppService(
            OrderEvaluateManager orderEvaluateManager,
            IRepository<OrderEvaluate> orderEvaluateRepository,
            IRepository<OrderDetail> orderDetailRepository
            )
        {
            _orderEvaluateManager = orderEvaluateManager;
            _orderEvaluateRepository = orderEvaluateRepository;
            _orderDetailRepository = orderDetailRepository;
        }

        /// <summary>
        /// 管理员进行评价
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(PermissionNames.OrderEvaluateManagement)]
        public async Task AdminEvaluate(EvaluateOrderDto input)
        {
            var admin = await GetCurrentUserAsync();
            var parentComment = await _orderEvaluateManager.Get(null, input.parentCommentId);
            await _orderEvaluateManager.AdminEvaluate(admin, new OrderEvaluate
            {
                Content = input.Content,
                Pictures = new Common.CustomValueType.ValueArray<string>(input.Pictures)
            }, parentComment);
        }

        /// <summary>
        /// 会员进行评价
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(PermissionNames.Member)]
        public async Task MemberEvaluate(EvaluateOrderDto input)
        {
            var member = await GetCurrentMemberAsync();
            var parentComment = await _orderEvaluateManager.Get(null, input.parentCommentId);
            await _orderEvaluateManager.AdminEvaluate(member, new OrderEvaluate
            {
                Content = input.Content,
                Pictures = new Common.CustomValueType.ValueArray<string>(input.Pictures)
            }, parentComment);
        }

        /// <summary>
        /// 得到会员的所有评论（列表，分页）
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<SearchResultDto<OrderEvaluateDto>> GetMemberEvaluates(SearchDto input)
        {
            var query = _orderEvaluateRepository.GetAll().Where(r => r.UserId == MemberId);
            var totalCount = query.Count();
            var items = query.OrderByDescending(r => r.CreationTime).Skip(input.SkipCount).Take(input.MaxResultCount).ToList();
            return new SearchResultDto<OrderEvaluateDto>
            {
                TotalCount = totalCount,
                Items = items.Select(r => new OrderEvaluateDto(r)).ToList()
            };
        }

        /// <summary>
        /// 得到与产品相关的评论，评论来自于订单（树，分页）
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<SearchResultDto<OrderEvaluateDto>> GetCommodityEvaluates(GetCommodityEvaluatesDto input)
        {
            var evaluates = _orderEvaluateRepository.GetAll().Where(r => r.ParentCommentId == null);
            var details = _orderDetailRepository.GetAll().Where(r => r.CommodityId == input.CommodityId);

            evaluates = evaluates.Join(details, e => e.OrderNumber, d => d.OrderNumber, (e, d) => e);

            var totalCount = evaluates.Count();
            var items = evaluates.OrderByDescending(r => r.CreationTime).Skip(input.SkipCount).Take(input.MaxResultCount).ToList();

            return new SearchResultDto<OrderEvaluateDto>
            {
                TotalCount = totalCount,
                Items = items.Select(r => new OrderEvaluateDto(r)).ToList()
            };
        }

        /// <summary>
        /// 得到评价的子评价（树， 分页)
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<SearchResultDto<OrderEvaluateDto>> GetChildEvaluates(GetChildEvaluatesDto input)
        {
            var query = _orderEvaluateRepository.GetAll().Where(r => r.ParentCommentId == input.ParentCommentId);
            var totalCount = query.Count();
            var items = query.OrderByDescending(r => r.CreationTime).Skip(input.SkipCount).Take(input.MaxResultCount).ToList();

            return new SearchResultDto<OrderEvaluateDto>
            {
                TotalCount = totalCount,
                Items = items.Select(r => new OrderEvaluateDto(r)).ToList()
            };
        }

        [AbpAuthorize(PermissionNames.OrderEvaluateManagement)]
        public async Task AdminDeleteEvaluate(EntityDto input)
        {
            await _orderEvaluateManager.AdminDeleteEvaluate(AdminId, input.Id);
        }

        [AbpAuthorize(PermissionNames.Member)]
        public async Task MemberDeleteEvaluate(EntityDto input)
        {
            await _orderEvaluateManager.AdminDeleteEvaluate(MemberId, input.Id);
        }
    }
}
